<template>
  <div>
    <el-button type="primary" icon="el-icon-plus" @click="addTrade"
      >添加按钮</el-button
    >
    <el-table :data="trademarkList" style="width: 100%; margin: 20px">
      <el-table-column type="index" label="序号" width="width" align="center">
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width">
      </el-table-column>
      <el-table-column label="品牌Logo" width="width">
        <template slot-scope="{ row, $index }">
          <img :src="row.logoUrl" alt="" width="80px" height="60px" />
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{ row, $index }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            circle
            size="mini"
            @click="updateTrade(row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            size="mini"
            @click="deleteTrade(row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="getTrademarkList"
      @size-change="handlerSizeChange"
      style="text-align: center"
      layout=" prev, pager, next, jumper, ->, total,slot,sizes"
      :total="total"
      :current-page="page"
      :pager-count="7"
      :page-size="3"
      :page-sizes="[3, 5, 10]"
    >
    </el-pagination>
    <el-dialog
      :title="tmForm.id ? '修改商品' : '添加商品'"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <el-form
        :rules="rules"
        label-width="80px"
        :model="tmForm"
        ref="tmForm"
        style="width: 80%"
      >
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌Logo" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="submitTradeForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var validatetmName = (rule, value, callback) => {
      if (value.length < 2 || value.length > 10) {
        return callback(new Error("品牌名称长度必须在2-10之间"));
      } else {
        callback();
      }
    };
    return {
      page: 1,
      limit: 3,
      total: 0,
      trademarkList: [],
      dialogVisible: false,
      tmForm: {
        tmName: "",
        logoUrl: "",
      },
      rules: {
        tmName: [
            { required: true, message: "品牌名称不得为空", trigger: "blur" },
            { validator: validatetmName, trigger: "change" },
        ],
        logoUrl: [
          { required: true, message: "请选择logo图片", trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    this.getTrademarkList();
  },
  methods: {
    async getTrademarkList(page = 1) {
      this.page = page;
      try {
        let result = await this.$API.trademark.getTrademarkList(
          this.page,
          this.limit
        );
        if (result.code === 200 || result.code === 20000) {
          this.trademarkList = result.data.records;
          this.total = result.data.total;
        }
      } catch (e) {
        this.$message.error("获取商品数据失败" + e.message);
      }
    },
    handlerSizeChange(size) {
      this.limit = size;
      this.getTrademarkList(this.page, this.limit);
    },
    addTrade() {
      this.dialogVisible = true;
    },
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        this.tmForm.logoUrl = res.data;
      } else {
        this.$message.error("上传失败");
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/jpg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG或者JPEG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    cancelDialog() {
      this.dialogVisible = false;
      this.tmForm = {
        tmName: "",
        logoUrl: "",
      };
    },
    updateTrade(row) {
      this.dialogVisible = true;
      this.tmForm = { ...row };
    },
    submitTradeForm() {
      this.$refs.tmForm.validate(async (valid) => {
        if (valid) {
          this.dialogVisible = false;
          try {
            let result = await this.$API.trademark.saveTrademark(this.tmForm);
            if (result.code === 20000 || result.code === 200) {
              this.$message.success(
                this.tmForm.id ? "修改商品成功" : "添加商品成功"
              );
              this.getTrademarkList(this.tmForm.id ? this.page : 1);
            }
          } catch (e) {
            this.$message.error(
              this.tmForm.id ? "修改商品失败" : "添加商品失败"
            );
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleClose() {
      this.dialogVisible = false;
      this.tmForm = {
        tmName: "",
        logoUrl: "",
      };
    },
    async deleteTrade(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await this.$API.trademark.deleteTrade(id);
            this.$message.success("删除成功");
            this.getTrademarkList(this.trademarkList.length > 1 ? this.page : this.page - 1);
          } catch (e) {
            this.$message.error("删除失败" + e.message);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>